package by.demchenko.sample.dataaccess.impl;

import by.demchenko.sample.dataaccess.base.FacultyDao;
import by.demchenko.sample.datamodel.Faculty;
import org.springframework.stereotype.Repository;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;

@Repository
public class FacultyDaoImpl extends AbstractDaoImpl<Integer, Faculty> implements FacultyDao {

	protected FacultyDaoImpl() {
		super(Faculty.class);
	}

    @Override
    public int getCount() {
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<Long> criteria = cBuilder.createQuery(Long.class);
        Root<Faculty> root = criteria.from(Faculty.class);

        criteria.select(cBuilder.count(root));

        TypedQuery<Long> query = getEm().createQuery(criteria);
        return query.getSingleResult().intValue();
    }

    @Override
    public List<Faculty> getAll() {
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<Faculty> criteria = cBuilder.createQuery(Faculty.class);
        Root<Faculty> root = criteria.from(Faculty.class);

        criteria.select(root);

        TypedQuery<Faculty> query = getEm().createQuery(criteria);
        List<Faculty> results = query.getResultList();
        return results;
    }
}